package com.prince.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.prince.bean.CommonWebResponse;
import com.prince.bean.ResultParams;
import com.prince.bean.WebCode;
import com.prince.mapper.CodeMapper;
import com.prince.mapper.x.CodeAllMapper;
import com.prince.model.Code;
import com.prince.model.CodeExample;
import com.prince.page.Page;
import com.prince.util.JsonUtil;
import com.prince.util.MapUtil;
import com.prince.util.StringUtil;
import com.prince.web.base.BaseService;
import com.prince.web.service.CodeService;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class CodeServiceImpl extends BaseService implements CodeService {

	@Resource
	private CodeMapper codeMapper;

	@Resource
	private CodeAllMapper codeAllMapper;
	

//	@Resource
//	private CodeCache codeCache;

	@Override
	public Map<String, Object> findCodeByPage(Map<String, Object> paramMap, Page page) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
         //判断参数是否为空
		if (null == paramMap || paramMap.size() == 0) {
			logger.debug("[CodeServiceImpl] findCodeByPage param beanJson is null");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}

		if (null == page) {
			logger.debug("[CodeServiceImpl] findCodeByPage page is null");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
        //封装查询条件参数
		CodeExample codeExample = new CodeExample();
		CodeExample.Criteria criteria = codeExample.createCriteria();
		paramMap.remove("startTime");
		paramMap.remove("page");
		paramMap.remove("rows");
		paramMap.remove("endTime");
        //反射封装参数
		StringUtil.reflectMap(criteria, paramMap);
		int total = codeMapper.countByExample(codeExample);
        logger.debug("[CodeServiceImpl] findCodeByPage 查询总记录数"+total);
		codeExample.setPage(page);
		codeExample.setOrderByClause("cteated desc");
		List<Code> list = codeMapper.selectByExample(codeExample);
		logger.debug("[CodeServiceImpl] findCodeByPage 返回结果"+JsonUtil.toJSONString(list));
		return response.toHashMapByPage(total, list);
	}

	@Override
	public Map<String, Object> addCode(Code code) {
        //根据所添写的内容判断是否重复
		CodeExample codeExample = new CodeExample();
		CodeExample.Criteria criteria = codeExample.createCriteria();
		//同一个分类下不重复即可
		criteria.andSortCodeEqualTo(code.getSortCode());
		if (StringUtil.isNotEmpty(code.getName())) {
			criteria.andNameEqualTo(code.getName());
		}

		List<Code> codeList = codeMapper.selectByExample(codeExample);
		if (!codeList.isEmpty()) {
			logger.debug("[addCode] insert Code duplicate name. Code={}", JSON.toJSONString(code));
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.duplicateName).toHashMap();
		}
		CodeExample CodeExampleOne = new CodeExample();
		CodeExample.Criteria criteriaOne = CodeExampleOne.createCriteria();
		//同一个分类下不重复即可
		criteriaOne.andSortCodeEqualTo(code.getSortCode());
		if (StringUtil.isNotEmpty(code.getCode())) {
			criteriaOne.andCodeEqualTo(code.getCode());
		}

		List<Code> CodeListOne = codeMapper.selectByExample(CodeExampleOne);
		if (!CodeListOne.isEmpty()) {
			logger.debug("[addCode] insert Code duplicate name. Code={}", JSON.toJSONString(code));
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.dataDuplication).toHashMap();
		}

		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		code.setCteated(new Date());
		logger.debug("[CodeServiceImpl] addCode  添加参数"+JsonUtil.toJSONString(code));
		int i = codeMapper.insertSelective(code);

		if (!(i > 0)) {
			logger.debug("[addCode] insert Code is fail. notice={}", JSON.toJSONString(code));
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		//清空缓存
//		codeCache.del();
		return response.toHashMap();
	}

	@Override
	public Map<String, Object> delCode(Code code) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        //根据id删除
		logger.debug("[CodeServiceImpl] del Code id={}"+code.getId());
		int i = codeMapper.deleteByPrimaryKey(code.getId());
		if (!(i > 0)) {
			logger.debug("[delCode] del Code is fail id={}", code.getId());
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		//清空缓存
//		codeCache.del();
		return response.toHashMap();
	}

	@Override
	public Map<String, Object> updateCode(Code code) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		//判断所更新是否重名
		if (StringUtil.isNotEmpty(code.getCode()) && StringUtil.isNotEmpty(code.getDescribed())
				&& !code.getCode().equals(code.getDescribed())) {
			CodeExample codeExample = new CodeExample();
			codeExample.createCriteria().andCodeEqualTo(code.getCode()).andSortCodeEqualTo(code.getSortCode());
			List<Code> list = codeMapper.selectByExample(codeExample);
			if (!list.isEmpty()) {
				code.setRemark(null);
				return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.duplicateName).toHashMap();
			}
		}
        logger.debug("[CodeServiceImpl] updateCode 参数为"+JsonUtil.toJSONString(code));
		int i = codeMapper.updateByPrimaryKeySelective(code);
		if (!(i > 0)) {

			logger.debug("[updateCode] update Code is fail id={}", code.getId());
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		//清空缓存
//		codeCache.del();
		return response.toHashMap();
	}

	@Override
	public Map<String, Object> findCodeByCondition(Code code) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        //添加查询条件
		CodeExample codeExample = new CodeExample();
		CodeExample.Criteria criteria = codeExample.createCriteria();
		if (null != code.getId()) {
			criteria.andIdEqualTo(code.getId());
		}
		if (null != code.getCode() && !code.getCode().equals("")) {
			criteria.andCodeEqualTo(code.getCode());
		}
		if (null != code.getSortCode() && !code.getSortCode().equals("")) {
			criteria.andSortCodeEqualTo(code.getSortCode());
		}
		logger.debug("[CodeServiceImpl] findCodeByCondition 参数为"+JsonUtil.toJSONString(code));
		List<Code> list = codeMapper.selectByExample(codeExample);
        //判断是否为空
		if (null == list || list.size() == 0) {
			logger.debug("[findCodeByCondition] find codetList is null");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		logger.debug("[CodeServiceImpl] findCodeByCondition 返回结果为"+JsonUtil.toJSONString(list));
		response.put("list", list);
		return response.toHashMap();
	}

	/* 
	 * 通过sortCode 查询code
	 * @see com.prince.service.back.service.CodeService#findCodeBySortCode(java.lang.String)
	 */
	@Override
	public Map<String, Object> findCodeBySortCode(String sortCode) {
		return this.findCodeBySortCode(sortCode, null);
	}

	
	/* 
	 * 通过sortCode 查询code   sort 排序
	 * @see com.prince.service.back.service.CodeService#findCodeBySortCode(java.lang.String, java.lang.String)
	 */
	@Override
	public Map<String, Object> findCodeBySortCode(String sortCode, String sort) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		if (StringUtil.isEmpty(sortCode)) {
			logger.debug("sortCode为空");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}

		CodeExample codeExample = new CodeExample();
		CodeExample.Criteria criteria = codeExample.createCriteria();
		criteria.andSortCodeEqualTo(sortCode);
		//是否排序
		if(StringUtil.isNotEmpty(sort)) {
			codeExample.setOrderByClause(" " + sort);
		}
        logger.debug("[CodeServiceImpl] findCodeBySortCode sortCode is"+sortCode);
		List<Code> list = codeMapper.selectByExample(codeExample);
         //判断是否为空
		if (null == list || list.size() == 0) {
			logger.debug(sortCode + "不存在");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
        logger.debug("[CodeServiceImpl] findCodeBySortCode 返回结果"+JsonUtil.toJSONString(list));
		response.put("data", list);
		return response.toHashMap();
	}
	
	@Override
	public Map<String, Object> findCodeListAndMap() {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
//		String codeValue = codeCache.get();
		String codeValue = null;
		//如果为空，循环添加进缓存
		if (StringUtil.isEmpty(codeValue)) {
			Map<String, Map<String, Object>> map = getCodeMap();
			codeValue = JSON.toJSONString(map);
			if (!StringUtil.isEmpty(codeValue)) {
				logger.info(map.toString());
//				codeCache.set(JSON.toJSONString(map));
			}
		}
		response.put("data", codeValue);
		return response.toHashMap();
	}
	@Override
	public Map<String, Map<String, Object>> getCodeMap() {
		Map<String, Map<String, Object>> map = new HashMap<String, Map<String, Object>>();
		//查询所有
		List<String> list = codeAllMapper.selectCodeAll();
		//循环加入集合
		for (int i = 0; i < list.size(); i++) {
			List<Code> lcode = codeAllMapper.selectCodeBySortCode(list.get(i));
			if (lcode != null && lcode.size() > 0) {
				Map<String, Object> s = new HashMap<String, Object>();
				for (int j = 0; j < lcode.size(); j++) {
					s.put(lcode.get(j).getCode(), lcode.get(j).getName());
				}
				map.put(list.get(i), s);
			}
		}
		return map;
	}

	@Override
	public Map<String, Map<String, Object>> getCodeMapRemark() {
		Map<String, Map<String, Object>> map = new HashMap<String, Map<String, Object>>();
		//查询所有code
		List<String> list = codeAllMapper.selectCodeAll();
		//循环把备注加入集合
		for (int i = 0; i < list.size(); i++) {
			List<Code> lcode = codeAllMapper.selectCodeBySortCode(list.get(i));
			if (lcode != null && lcode.size() > 0) {
				Map<String, Object> s = new HashMap<String, Object>();
				for (int j = 0; j < lcode.size(); j++) {
					s.put(lcode.get(j).getCode(), lcode.get(j).getRemark());
				}
				map.put(list.get(i), s);
			}
		}
		return map;
	}

	@Override
	public Code findCodeByCode(String code) {
		CodeExample codeExample = new CodeExample();
		CodeExample.Criteria criteria = codeExample.createCriteria();
		if(!StringUtil.isEmpty(code)){
			criteria.andCodeEqualTo(code);
		}
		List<Code> codes = codeMapper.selectByExample(codeExample);
		return null==codes||codes.size()==0?null:codes.get(0);
	}

	@Override
	public List<Code> findCodeBySortCode1(String sortCode) {

		CodeExample codeExample = new CodeExample();
		CodeExample.Criteria criteria = codeExample.createCriteria();
		criteria.andSortCodeEqualTo(sortCode);
        logger.debug("[CodeServiceImpl] findCodeBySortCode sortCode is"+sortCode);
		List<Code> list = codeMapper.selectByExample(codeExample);
		return list;
	}
	@Override
	public List<Code> findDictCodeList(Map<String, Object> param) {
		CodeExample codeExample = new CodeExample();
		CodeExample.Criteria criteria = codeExample.createCriteria();
		if(MapUtil.isNotEmpty(param, "sortCodes")) {
			String sortCodes = MapUtils.getString(param, "sortCodes");
			criteria.andSortCodeIn(Arrays.asList(sortCodes.split(",")));
		}
		List<Code> list = codeMapper.selectByExample(codeExample);
		return list;
	}
}
